﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk;
using System.Windows.Forms;
using Microsoft.Xrm.Sdk.Discovery;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using CrmCustomizationsExcelAddIn.Data;
using CrmCustomizationsExcelAddIn.Helper;
using CrmCustomizationsExcelAddIn.Data.Fetchxml;

namespace CrmCustomizationsExcelAddIn
{
    public partial class CrmCustomizationsRibbon
    {


        public void enableRibbonButtons()
        {
            btnPublishAll.Enabled = true;
            btnUpdateSheet.Enabled = true;
            btnExportChanges.Enabled = true;
            btnSynchronizeEntity.Enabled = true;
            btnGetEntitiesList.Enabled = true;
        }


        private void btnConnect_Click(object sender, RibbonControlEventArgs e)
        {

            CrmAuthenticationForm CrmAuthenticationForm = new CrmAuthenticationForm(this);
            CrmAuthenticationForm.ShowDialog();
        }

        private void btnExportChanges_Click(object sender, RibbonControlEventArgs e)
        {
            if (Globals.CrmAddIn.excelHelper.IsEditing())
            {
                MessageBox.Show("Plesea exit from edit-mode", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            CrmCreateConfirm confirmUpdate = new CrmCreateConfirm();
            confirmUpdate.ShowDialog();
        }


        private void btnUpdateSheet_Click(object sender, RibbonControlEventArgs e)
        {
            if (Globals.CrmAddIn.excelHelper.IsEditing())
            {
                MessageBox.Show("Plesea exit from edit-mode", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            refreshCurrentSheet();
        }

        public void refreshCurrentSheet()
        {
            if (GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet() != null)
            {
                GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet().language = GlobalApplicationData.Instance.currentLanguage;
                switch (GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet().sheetType)
                {
                    case ExcelSheetInfo.ExcelSheetType.attribute:
                        {
                            EntityMetadata currentEntity = Globals.CrmAddIn.crmOpHelper.RetriveEntityAtrribute(((AttributeExcelSheetsInfo)GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet()).entityMedata.LogicalName);
                            ((AttributeExcelSheetsInfo)GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet()).entityMedata = currentEntity;
                            IEnumerable<string> formAttr = Globals.CrmAddIn.crmOpHelper.GetAttributeOfTheMainForm(currentEntity.ObjectTypeCode.Value);
                            Globals.CrmAddIn.excelHelper.refreshAttributeSheeet(GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet(), currentEntity, GlobalApplicationData.Instance.allEntities, formAttr);
                            break;
                        }
                    case ExcelSheetInfo.ExcelSheetType.optionSet:
                        {
                            OptionSetExcelSheetsInfo currentOption = (OptionSetExcelSheetsInfo)GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet();
                            EntityMetadata currentEntity = Globals.CrmAddIn.crmOpHelper.RetriveEntityAtrribute(currentOption.parentAttribute.EntityLogicalName);

                            IEnumerable<AttributeMetadata> currentOpt = currentEntity.Attributes.Where(x => x is EnumAttributeMetadata && ((EnumAttributeMetadata)x).OptionSet != null && ((EnumAttributeMetadata)x).OptionSet.MetadataId.ToString() == currentOption.objectName);

                            if (currentOpt.Count() > 0)
                            {
                                currentOption.optionData = ((EnumAttributeMetadata)currentOpt.First()).OptionSet;
                                Globals.CrmAddIn.excelHelper.refreshOptionSetSheet((ExcelSheetInfo)currentOption);
                            }
                            break;
                        }
                    case ExcelSheetInfo.ExcelSheetType.entity:
                        {
                            ExcelSheetInfo sheet = GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet();
                            GlobalOperations.FilterBySolution(GlobalApplicationData.Instance.currentSolution.SolutionName);
                            EntityMetadata[] allEntities = GlobalOperations.getEntitiesWithAttributes();
                            GlobalApplicationData.Instance.allEntities = allEntities.OrderBy(p => Utils.getLocalizedLabel(p.DisplayName.LocalizedLabels, sheet.language)).ToArray();
                            Globals.CrmAddIn.excelHelper.refreshEntitySheeet(sheet, allEntities);
                            break;
                        }
                    case ExcelSheetInfo.ExcelSheetType.form:
                        {
                            GlobalOperations.RefreshCurrentFormSheet();
                            break;
                        }
                    case ExcelSheetInfo.ExcelSheetType.view:
                        {
                            GlobalOperations.RefreshCurrentViewSheet();
                            break;
                        }
                }
            }
        }

        private void btnSynchronizeEntity_Click(object sender, RibbonControlEventArgs e)
        {
            if (Globals.CrmAddIn.excelHelper.IsEditing())
            {
                MessageBox.Show("Plesea exit from edit-mode", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            Worksheet sheet = Globals.CrmAddIn.excelHelper.getCurrentSheet();
            ExcelSheetInfo.ExcelSheetType type;
            string name;
            string orgprefix;
            int language;
            if (!Globals.CrmAddIn.excelHelper.readSettingRow(sheet, out name, out type, out orgprefix, out language)) return;
            if (type == ExcelSheetInfo.ExcelSheetType.attribute)
            {
                EntityMetadata currentEntity = Globals.CrmAddIn.crmOpHelper.RetriveEntityAtrribute(name);
                if (currentEntity != null)
                {
                    GlobalApplicationData.Instance.eSheetsInfomation.addSheetAndSetAsCurrent(new AttributeExcelSheetsInfo(ExcelSheetInfo.ExcelSheetType.attribute, sheet, currentEntity), name);
                    GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet().orgPrefix = orgprefix;
                    GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet().language = language;
                }
                else
                {
                    MessageBox.Show("Entity not Found Impossible To syncronize", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (type == ExcelSheetInfo.ExcelSheetType.optionSet)
            {
                // to be implemented
            }
        }

        private void btnGetEntitiesList_Click(object sender, RibbonControlEventArgs e)
        {
            if (Globals.CrmAddIn.excelHelper.IsEditing())
            {
                MessageBox.Show("Plesea exit from edit-mode", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            GlobalOperations.CreatenNewEntitySheet();
            if (Globals.CrmAddIn.TaskPane.Visible == false)
            {
                Globals.CrmAddIn.TaskPane.Visible = true;
                ((ActionPanelEntityList)Globals.CrmAddIn.TaskPane.Control).showLoading(true);
                GlobalOperations.LoadOperations();
                ((ActionPanelEntityList)Globals.CrmAddIn.TaskPane.Control).FillEntitiesList();
            }
        }

        private void btnPublishAll_Click(object sender, RibbonControlEventArgs e)
        {
            Globals.CrmAddIn.crmOpHelper.publishRequest();
        }
    }
}
